package com.dongdongshop.controller;

import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@RocketMQMessageListener(topic = "SMS",consumerGroup = "xiaoxi")
public class SMSController implements RocketMQListener<String>  {

    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    public void onMessage(String phone) {

//        自动生成验证码
        String code = RandomStringUtils.randomNumeric(4);

//初始化clnt,使用单例方式
        YunpianClient clnt = new YunpianClient("6b3ee03d0f730196184864e960e826db").init();



//发送短信APISS
        Map<String, String> param = clnt.newParam(2);
        param.put(YunpianClient.MOBILE, phone);
        param.put(YunpianClient.TEXT, "【彭斌】亲爱的用户您好，您的验证码是"+ code +"。有效期为30分钟，请尽快验证");
        Result<SmsSingleSend> r = clnt.sms().single_send(param);
//获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
        System.out.println("返回码"+r.getCode());
        System.out.println("返回码描述"+r.getMsg());
        System.out.println("API结果"+r.getData());
//账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*

//释放:clnt.close() 释放后clnt将无法再使用
        clnt.close();


//        放置redis
        String key = phone;
        String feild = code;
//        放置消息
        BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(key);
        boundValueOperations.set(feild);
        redisTemplate.expire(key,30, TimeUnit.MINUTES);


    }


}
